package com.xian.ucenter.controller.front;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xian.ucenter.annotation.PostView;
import com.xian.ucenter.commons.Result;
import com.xian.ucenter.entities.Post;
import com.xian.ucenter.entities.vo.PostQuery;
import com.xian.ucenter.entities.vo.PostTagVo;
import com.xian.ucenter.entities.vo.PostVo;
import com.xian.ucenter.service.PostService;
import com.xian.ucenter.service.TagService;
import com.xian.ucenter.service.impl.PostServiceImpl;
import com.xian.ucenter.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 文章管理表 前端控制器
 * </p>
 *
 * @author xian
 * @since 2022/07/23 02:59
 */
@CrossOrigin
@RestController
@RequestMapping("/ucenter/front/post")
public class PostFrontController {
    @Autowired
    private PostServiceImpl postService;
    @Autowired
    private TagService tagService;
    @GetMapping("/{current}")
    public Result getAuthPosts(@PathVariable("current") Integer current) {
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<>();
        Page<Post> page = pageList(current, 6, postQueryWrapper);
        List<PostVo> list = BeanUtil.copyToList(page.getRecords(), PostVo.class);
        list.forEach(postVo -> {
            postVo.setList(tagService.getTagNamesByPostId(postVo.getId()));
        });
        return Result.ok().data("total",page.getTotal()).data("pages",page.getPages()).data("current",page.getCurrent()).data("list",list);
    }
    @PostView
    @GetMapping("/getPost/{postId}")
    public Result getPost(@PathVariable("postId") String postId) {
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<>();
        postQueryWrapper.eq("id",postId);
        postQueryWrapper.eq("status",0);
        Post one = postService.getOne(postQueryWrapper);
        if (ObjectUtil.isNull(one)){
            throw new RuntimeException("帖子不存在！");
        }
        PostTagVo postTagVo = BeanUtil.copyProperties(one, PostTagVo.class);
        postTagVo.setTagList(tagService.getTagByPostId(postTagVo.getId()));
        return Result.ok("post",postTagVo);
    }

    public Page<Post> pageList(Integer current, Integer count, Wrapper<Post> wrapper) {
        Page<Post> page = new Page<>(current,count);
        postService.page(page,wrapper);
        return page;
    }

}
